<template>
  <div class="min-h-screen" :class="paymentStyle.bgClass">
    <!-- 顶部标题 -->
    <div class="py-4 text-center" :class="paymentStyle.headerClass">
      <h1 class="text-2xl font-bold" :class="paymentStyle.textClass">{{ paymentStyle.title }}</h1>
    </div>

    <div class="max-w-md mx-auto p-4">
      <!-- 收银台 -->
      <a-card class="mb-4 shadow-sm" :bordered="false" :class="paymentStyle.cardClass">
        <!-- 金额输入区域 -->
        <div class="mb-6">
          <div class="text-gray-500 mb-2">请输入支付金额</div>
          <div class="flex items-center">
            <span class="text-2xl font-bold mr-2">¥</span>
            <a-input-number
              v-model:value="amount"
              :precision="2"
              :min="0.01"
              :max="50000"
              class="text-2xl font-bold flex-1"
              :class="paymentStyle.inputClass"
              placeholder="请输入金额"
              style="width: 100%;"
            />
          </div>
        </div>

        <!-- 备注信息 -->
        <div class="mb-6">
          <div class="text-gray-500 mb-2">备注信息（选填）</div>
          <a-input
            v-model:value="description"
            placeholder="请输入备注信息"
            :class="paymentStyle.inputClass"
          />
        </div>

        <!-- 付款按钮 -->
        <a-button
          type="primary"
          block
          size="large"
          :disabled="!amount || amount <= 0 || !userId"
          :class="paymentStyle.buttonClass"
          @click="handlePay"
        >
          立即支付
        </a-button>

        <!-- 显示用户ID -->
        <div v-if="userId" class="mt-4 text-center text-sm text-gray-500">
          用户ID: {{ userId }}
        </div>

        <!-- 显示支付信息 -->
        <div v-if="userId" class="mt-4">
          <a-descriptions title="支付信息" bordered>
            <a-descriptions-item label="订单号">
              {{ orderNo }}
            </a-descriptions-item>
            <a-descriptions-item label="支付金额">
              ¥{{ amount }}
            </a-descriptions-item>
            <a-descriptions-item label="支付渠道">
              支付宝支付
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 订单信息
const orderNo = ref(route.query.orderNo as string)
const timestamp = ref(route.query.timestamp as string)
const nonce = ref(route.query.nonce as string)
const sign = ref(route.query.sign as string)

// 支付信息
const amount = ref<number>(0.01)
const description = ref('')
const userId = ref<string>('')

// 根据支付渠道设置不同的样式
const paymentStyle = computed(() => {
  return {
    bgClass: 'bg-gray-50',
    headerClass: 'bg-blue-500',
    textClass: 'text-white',
    cardClass: '',
    inputClass: 'border-blue-500 focus:border-blue-600',
    buttonClass: 'bg-blue-500 hover:bg-blue-600 border-blue-500',
    title: '支付宝支付'
  }
})

// 声明支付宝JSBridge类型
declare global {
  interface Window {
    AlipayJSBridge?: {
      call: (api: string, params: any, callback: (result: any) => void) => void;
    };
  }
}

// 验证签名
const verifySign = async () => {
  try {
    const response = await axios.post('/api/merchant/verify-sign', {
      orderNo: orderNo.value,
      timestamp: timestamp.value,
      nonce: nonce.value,
      sign: sign.value
    })
    return response.data.code === 0
  } catch (error) {
    console.error('验证商户请求签名失败:', error)
    return false
  }
}

// 验证URL参数
const validateUrlParams = async () => {
  // 1. 检查必要参数是否存在
  // if (!orderNo.value || !nonce.value || !sign.value) {
  //   message.error('缺少必要参数')
  //   return false
  // }

  // 2. 验证签名
  const isValidSign = await verifySign()
  if (!isValidSign) {
    message.error('验证商户请求签名失败')
    return false
  }

  return true
}

// 获取支付宝用户ID
const getAlipayUserId = async () => {
  try {
    // 1. 检查是否在支付宝环境
    if (!window.AlipayJSBridge) {
      message.error('请在支付宝客户端中打开')
      return false
    }

    // 2. 检查URL中是否已有授权码
    const code = route.query.auth_code as string
    if (code) {
      // 3. 使用授权码获取用户ID
      const response = await axios.post('/api/auth/alipay/user', {
        authCode: code
      })

      if (response.data.code === 0) {
        userId.value = response.data.data.userId
        message.success('获取用户ID成功')
        return true
      } else {
        message.error(response.data.message || '获取用户ID失败')
        return false
      }
    } else {
      // 4. 如果没有授权码，生成授权链接并跳转
      const redirectUri = encodeURIComponent(window.location.href)
      const response = await axios.get(`/api/auth/alipay/url?redirectUri=${redirectUri}`)

      if (response.data.authUrl) {
        window.location.href = response.data.authUrl
      }
      return false
    }
  } catch (error) {
    console.error('获取用户ID失败:', error)
    message.error('获取用户ID失败')
    return false
  }
}

// 处理支付
const handlePay = async () => {
  try {
    // 1. 输入金额验证
    if (!amount.value || amount.value <= 0) {
      message.error('请输入有效金额')
      return
    }

    if (!userId.value) {
      message.error('请先获取用户ID')
      return
    }

    // 2. 调用统一下单接口
    const response = await axios.post('/api/alipay/v1/payments/jsapi', {
      orderNo: orderNo.value,
      amount: amount.value,
      description: description.value || '商品购买',
      userId: userId.value
    })

    if (response.data.code === 0) {
      // 3. 调用支付接口
      const payParams = response.data.data.payParams

      if (!window.AlipayJSBridge) {
        throw new Error('请在支付宝客户端中打开')
      }

      window.AlipayJSBridge.call('tradePay', {
        tradeNO: payParams.tradeNo
      }, function(result: { resultCode: string; memo: string }) {
        if (result.resultCode === '9000') {
          message.success('支付成功')
          // 直接返回支付宝首页
          window.AlipayJSBridge.call('popWindow', {}, function() {
            // 回调函数可以为空
          })
        } else {
          message.error('支付失败：' + result.memo)
          // 跳转到支付失败页面
          router.push(`/pay/fail?orderNo=${orderNo.value}&error=${result.memo}`)
        }
      })
    } else {
      message.error(response.data.message || '创建支付订单失败')
    }
  } catch (error: any) {
    console.error('支付过程发生错误:', error)
    message.error(error.response?.data?.message || '支付失败，请重试')
  }
}

// 页面加载时验证参数并获取用户ID
onMounted(async () => {
  // 1. 验证URL参数
  const isValid = await validateUrlParams()
  if (!isValid) {
    return
  }

  // 2. 获取用户ID
  await getAlipayUserId()
})
</script>

<style scoped>
.ant-card {
  border-radius: 8px;
}

.ant-descriptions-item-label {
  width: 120px;
  color: #666;
}
</style>